<!--
 * @Author: yanjikun
 * @Date: 2022-06-07 10:12:21
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-07 15:14:07
 * @Description: file content
-->

<script lang="tsx">
  import { Dropdown, Menu, Tree } from 'ant-design-vue'
  import { isBoolean, isFunction } from 'lodash'
  import { computed, defineComponent, unref } from 'vue'
  import { basicTreeProps } from './basic-tree'
  import { useTreeState } from './hooks/useTreeState'

  export default defineComponent({
    name: 'BasicTree',
    props: basicTreeProps,
    components: {
      Tree,
      Menu,
      Dropdown,
    },
    setup(props, { slots }) {
      const treeState = useTreeState({ props, slots })
      const { treeData, getBindValues } = treeState
      const contextMenu = (data) => {
        const treeParams = {
          record: data,
          text: data.title,
          index: data.key,
        }
        const menuActions = computed(() => {
          return props.menuActions.filter(({ hidden }) => {
            if (isBoolean(hidden)) {
              return !hidden
            }
            if (isFunction(hidden)) {
              return !hidden(treeParams)
            }
          })
        })
        const onContextMenuClick = (key: number) => {
          const action = unref(menuActions)[key]
          if (isFunction(action.onClick)) {
            action.onClick(treeParams)
          }
        }
        return (
          <Dropdown trigger={['contextmenu']}>
            {{
              default: () => <span>{data.title}</span>,
              overlay: () => (
                <Menu onclick={({ key: menuKey }) => onContextMenuClick(menuKey)}>
                  {unref(menuActions).map((item, index) => (
                    <Menu.Item key={index}>{item.label}</Menu.Item>
                  ))}
                </Menu>
              ),
            }}
          </Dropdown>
        )
      }
      return () => (
        <Tree treeData={unref(treeData)} {...unref(getBindValues)}>
          {{ title: (data) => contextMenu(data) }}
        </Tree>
      )
    },
  })
</script>

<style scoped lang="less"></style>
